package com.panfeng.xcloud.scheduler.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.panfeng.xcloud.common.core.constants.BlConstants;
import com.panfeng.xcloud.scheduler.dto.TronBlockNumberDTO;
import com.panfeng.xcloud.scheduler.service.IUpdateNewestBlockNumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigInteger;

@Service
@Slf4j
public class UpdateNewestBlockNumServiceImpl implements IUpdateNewestBlockNumService {

    @Autowired
    @Qualifier(value = "notLoadBalancedRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 刷新最新区块高度
     */
    @Override
    public void updateNewestBlockNum() {
        TronBlockNumberDTO nowBlockNumber = getNowBlockNumber();
        if (nowBlockNumber == null) {
            return;
        }
        updateNewestBlockNum(nowBlockNumber.getBlockerNumber());
    }

    //更新当前最新的区块
    private void updateNewestBlockNum(BigInteger blockNum) {
        redisTemplate.opsForValue().set(BlConstants.REDIS_KEY_NEWEST_BLOCK_NUM, blockNum.toString());
    }


    public TronBlockNumberDTO getNowBlockNumber() {
        String url = "https://api.trongrid.io/wallet/getnowblock";
        String result = restTemplate.getForObject(url, String.class);
        JSONObject object = JSONObject.parseObject(result);
        if (null == object) {
            return null;
        }
        JSONObject blockHeader = object.getJSONObject("block_header");
        JSONObject rawData = blockHeader.getJSONObject("raw_data");

        BigInteger blockNum = rawData.getBigInteger("number");
        Long timestamp = rawData.getLong("timestamp");

        TronBlockNumberDTO dto = new TronBlockNumberDTO();
        dto.setBlockerNumber(blockNum);
        dto.setTimeStamp(timestamp);
        return dto;
    }

}
